package com.tarena.lbs.attach.service.impl;

import com.tarena.lbs.attach.config.FileConfig;
import com.tarena.lbs.attach.entity.AttachFile;
import com.tarena.lbs.attach.mapper.AttachFileMapper;
import com.tarena.lbs.attach.service.FileService;
import com.tarena.lbs.attach.util.FileUtil;
import com.tarena.lbs.attach.util.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileConfig fileConfig;

    @Autowired
    private AttachFileMapper attachFileMapper;

    @Override
    @Transactional
    public AttachFile saveFile(MultipartFile file) throws IOException {
        // 生成文件ID
        String fileId = IdGenerator.generateFileId();

        // 创建文件存储目录
        String relativePath = FileUtil.generateRelativePath(fileId);
        Path filePath = Paths.get(fileConfig.getDir(), relativePath);
        Files.createDirectories(filePath.getParent());

        // 保存文件
        file.transferTo(filePath);

        // 保存文件记录
        AttachFile attachFile = new AttachFile();
        attachFile.setFileId(fileId);
        attachFile.setOriginalName(file.getOriginalFilename());
        attachFile.setFileType(file.getContentType());
        attachFile.setFileSize(file.getSize());
        attachFile.setFilePath(relativePath);
        attachFile.setAccessUrl(fileConfig.getAccessUrl() + "/" + relativePath);
        attachFile.setCreateTime(LocalDateTime.now());
        attachFile.setExpireTime(LocalDateTime.now().plusDays(30));

        attachFileMapper.insert(attachFile);

        return attachFile;
    }

    @Override
    @Transactional
    public boolean deleteFile(String fileId) {
        AttachFile attachFile = attachFileMapper.selectByFileId(fileId);
        if (attachFile == null) {
            return false;
        }

        // 删除物理文件
        Path filePath = Paths.get(fileConfig.getDir(), attachFile.getFilePath());
        try {
            Files.deleteIfExists(filePath);
        } catch (IOException e) {
            throw new RuntimeException("删除文件失败", e);
        }

        // 删除数据库记录
        return attachFileMapper.deleteByFileId(fileId) > 0;
    }

    @Override
    public boolean bindFileToEntity(String fileId, String entityType, Long entityId) {
        return attachFileMapper.bindFileToEntity(fileId, entityType, entityId) > 0;
    }

    @Override
    public void cleanExpiredFiles() {
        List<AttachFile> expiredFiles = attachFileMapper.selectExpiredFiles(LocalDateTime.now());
        expiredFiles.forEach(file -> deleteFile(file.getFileId()));
    }
}